<script setup>
import Topbar from "@/components/Topbar/index.vue";
import FormTitle from "@/components/Form/FormTitle.vue";
import Form from "@/components/Form/index.vue";
import { ref } from "vue";
import TabList from "./components/TabList/index.vue";
import PreTree from "./components/PreTree/index.vue";
import { ElMessage } from "element-plus";
import {
  getSysPermissionList,
  addRole,
  queryRoleDetails,
  modifyRole,
} from "@/api/System";
import { buildTree } from "@/utils/common";
import { useRoute } from "vue-router";
const baseformRef = ref();
const route = useRoute();
const checkList = ref([]);
const baseformList = ref([
  {
    type: "input",
    key: "roleName",
    label: "角色名称",
    width: "260px",
    clearable: true,
    maxlength: "20",
  },
  {
    type: "input",
    key: "roleRemark",
    label: "备注",
    width: "260px",
    clearable: true,
    maxlength: "100",
  },
]);

const baseformRules = {
  roleName: [{ required: true, message: "请输入员工姓名", trigger: "change" }],
};
const originData = ref([]);
const saveLoading = ref(false);
const sumbit = async () => {
  Promise.all([baseformRef.value?.submitForm()]).then((res) => {
    if (res.map((v) => v.state).some((v) => !v)) {
      const item = res.filter((v) => !v.state)[0].data;
      const messages = Object.values(item)[0];
      return ElMessage({
        showClose: true,
        message: messages[0].message,
        type: "error",
      });
    }
    sumbitEnd(res);
  });
};
const permissionIds = computed(() => {
  return Array.from(new Set(checkList.value.map((v) => v.data).flat()));
});
// 最后提价处理
const sumbitEnd = async (res) => {
  if (!permissionIds.value.length) {
    return ElMessage.error("至少勾选一个菜单");
  }
  let obj = {};
  res
    .map((v) => v.data)
    .forEach((e) => {
      obj = { ...obj, ...e };
    });
  saveLoading.value = true;
  await modifyRole({
    ...obj,
    permissionIds: [...btnPermissionList.value, ...permissionIds.value],
    id: uuid.value,
  });
  saveLoading.value = false;
  sessionStorage.setItem("closeTagName", "RoleManageEdit");
  closeBack();
};
const treeData = ref([]);
const tabsItem = ref({});
const changeFun = (item) => {
  tabsItem.value = item;
};
const preTreeRef = ref();

const topBarRef = ref();
const closeBack = () => {
  topBarRef.value.backHandle();
};
const tabsList = ref([]);
const btnPermissionList = ref([]);
const uuid = computed(() => {
  return route.query.uuid;
});
onActivated(async () => {
  checkList.value = [];
  const res = await getSysPermissionList();
  originData.value = res; //.filter(v=>v.permissionType != 'B')
  btnPermissionList.value = res
    .filter((v) => v.permissionType == "B")
    .map((v) => v.id);
  tabsList.value = originData.value.filter(
    (v) =>
      v.parentId == "0" &&
      v.permissionName != "Hello" &&
      v.permissionName != "bad-not-found"
  );
  tabsList.value.forEach((e) => {
    e.state = false;
    tabsList.value[0].state = true;
  });
  tabsItem.value = tabsList.value[0];
  treeData.value = buildTree(
    originData.value
      .filter(
        (item) =>
          item.permissionName != "Hello" &&
          item.permissionName != "bad-not-found" &&
          item.permissionType != "B"
      )
      .map((v) => ({
        ...v,
        label: v.permissionLabel,
      }))
  );
  const { permissionIds, roleName, roleRemark } = await queryRoleDetails(
    uuid.value
  );
  preTreeRef.value.setChecks(permissionIds);
  tabsList.value.forEach((e) => {
    const tree = treeData.value.find((v) => v.id == e.id);
    checkList.value.push({
      tab: e,
      data: getAllIds([tree]).filter((s) => permissionIds.includes(s)),
    }); //
  });

  baseformRef.value.setForm({ roleName, roleRemark });
});

// 定义一个递归函数，用于获取所有 id 值
const getAllIds = (tree) => {
  const ids = [];
  for (const node of tree) {
    ids.push(node.id);
    if (node.children.length > 0) {
      const childrenIds = getAllIds(node.children);
      ids.push(...childrenIds);
    }
  }

  return ids;
};

const preTreeChange = (datas) => {
  if (
    !checkList.value.length ||
    !checkList.value.some((v) => v.tab.id == datas.tab.id)
  ) {
    checkList.value.push(datas);
  }
  checkList.value.forEach((v) => {
    if (v.tab.id == datas.tab.id) {
      v.data = datas.data;
    }
  });
  preTreeRef.value.setChecks(permissionIds.value);
};
</script>
<template>
  <Topbar ref="topBarRef" :tabName="'编辑角色'">
    <template #operate>
      <el-button style="min-width: 68px" @click="closeBack">取消</el-button>
      <el-button
        type="primary"
        style="min-width: 68px"
        @click="sumbit"
        :loading="saveLoading"
        >保存</el-button
      >
    </template>
  </Topbar>
  <div class="pl24 pt24 pr24 content_mians">
    <FormTitle class="mb16" :titleName="'基础信息'"></FormTitle>
    <Form
      ref="baseformRef"
      :formList="baseformList"
      :formRules="baseformRules"
      labelWidth="80px"
      isInline
      :isCustomizeClass="'grid grid-template-columns-3 grid-gap-39'"
    ></Form>
    <FormTitle class="mb16 mt8" :titleName="'菜单权限'"></FormTitle>
    <TabList class="mb16" @change="changeFun" :orginList="tabsList"></TabList>
    <PreTree
      ref="preTreeRef"
      :originData="treeData"
      :tab="tabsItem"
      @change="preTreeChange"
    ></PreTree>
  </div>
</template>

<style lang="less" scoped>
.content_mians {
  height: calc(100% - 80px);
  overflow: auto;
}
</style>
